package com.yuezhi.mylauncher.utils;

import static android.content.Context.ACTIVITY_SERVICE;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.yuezhi.mylauncher.activities.SettingActivity;
import com.yuezhi.mylauncher.base.BaseApplication;
import com.yuezhi.mylauncher.dialogs.QuitDialog;

import java.util.List;
import java.util.Random;

public class AppUtils {

    private static final String TAG = AppUtils.class.getSimpleName();
    @SuppressLint("StaticFieldLeak")
    private static QuitDialog quitDialog;
    @SuppressLint("StaticFieldLeak")
    private static Activity activity;


    public static void init(Activity activity) {
        AppUtils.activity = activity;
    }

    /**
     * 根据包名启动应用
     *
     * @param context     上下文
     * @param packageName 包名
     */
    public static void startApps(Context context, String packageName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            if (intent == null) {
                System.err.println("TimerV package: " + packageName + " uninstalled!");
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println("TimerV start package: " + packageName + " error!");
        }
    }

    /**
     * 全屏设置
     *
     * @param activity 传递全屏的Activity
     */
    public static void fullScreen(Activity activity) {
        // 去掉窗口标题
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏顶部的状态栏
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        hideBottomUIMenu(activity);
        activity.getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(visibility -> hideBottomUIMenu(activity));
        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 隐藏虚拟按键，并且全屏
     *
     * @param activity 传递需要隐藏的Activity
     */
    protected static void hideBottomUIMenu(Activity activity) {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else {
            //for new api versions.
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 展示打开系统设置所需要的密码输入弹窗
     *
     * @param context 上下文
     * @return 返回弹窗实例
     */
    public static QuitDialog showSettingDialog(Context context) {
        quitDialog = new QuitDialog(context);
        quitDialog.show();
        return quitDialog;
    }

    /**
     * 多次点击
     *
     * @param context 上下文
     * @param view    要点击的View
     */
    public static void showSetting(final Context context, final View view) {
        if (view != null) {
            view.setOnClickListener(new View.OnClickListener() {
                final static int COUNTS = 5;
                final static long DURATION = 2 * 1000;
                final long[] mHits = new long[COUNTS];

                @Override
                public void onClick(View v) {
                    System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                    mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                    if (mHits[0] >= (SystemClock.uptimeMillis() - DURATION)) {
                        view.setEnabled(false);
                        view.setClickable(false);
                        view.setFocusable(false);
                        view.setFocusableInTouchMode(false);
                        QuitDialog quitDialog = AppUtils.showSettingDialog(context);
                        quitDialog.setOnDismissListener(dialog -> {
                            view.setEnabled(true);
                            view.setClickable(true);
                            view.setFocusable(true);
                            view.setFocusableInTouchMode(true);
                        });
                    }
                }
            });
        }
    }

    public static void dismissDialog() {
        if (quitDialog != null && quitDialog.isShowing()) {
            quitDialog.dismiss();
        }
    }

    /**
     * 生成count位随机数
     *
     * @param count 随机数位数
     * @return String   返回随机数
     */
    public static String getCode(int count) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < count; i++) {
            stringBuilder.append(new Random().nextInt(10));
        }
        return stringBuilder.toString();
    }

    /**
     * 获取版本名称
     *
     * @param context 上下文
     * @return 版本名称
     */
    public static String getVersionName(Context context) {
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取包信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //返回版本号
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取版本号
     *
     * @param context 上下文
     * @return 版本号
     */
    public static int getVersionCode(Context context) {
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取包信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 0);
            //返回版本号
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static void startSettingActivity() {
        if (AppUtils.activity != null) {
            AppUtils.activity.startActivity(new Intent(AppUtils.activity, SettingActivity.class));
        }
    }

    public static boolean appOnForeground() {
        ActivityManager activityManager = (ActivityManager) BaseApplication.getContext().getSystemService(ACTIVITY_SERVICE);
        String packageName = "com.yuezhi.bancard";
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses == null)
            return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName) && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    public static void openSetting() {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        BaseApplication.getContext().startActivity(intent);
    }

    public static void setTopApp(Context context) {
        String packageName = "com.yuezhi.bancard";
        //获取ActivityManager
        ActivityManager mAm = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        //获得当前运行的task
        List<ActivityManager.RunningTaskInfo> taskList = mAm.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo rti : taskList) {
            //找到当前应用的task，并启动task的栈顶activity，达到程序切换到前台
            if (rti.topActivity.getPackageName().equals(packageName)) {
                mAm.moveTaskToFront(rti.id, 0);
                return;
            }
        }
    }

    public static String getLauncherPackageName(Context context) {
        final Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        final ResolveInfo res = context.getPackageManager().resolveActivity(intent, 0);
        if (res.activityInfo == null) {
            // should not happen. A home is always installed, isn't it?
            return null;
        }
        if (res.activityInfo.packageName.equals("android")) {
            // 有多个桌面程序存在，且未指定默认项时；
            return null;
        } else {
            return res.activityInfo.packageName;
        }
    }

    public static boolean isAppInstall(String packageName) {
        if (!TextUtils.isEmpty(packageName)) {
            try {
                activity.getPackageManager().getApplicationInfo(packageName, 0);
                return true;
            } catch (PackageManager.NameNotFoundException e) {
                try {
                    activity.getPackageManager().getApplicationInfo(packageName, 0);
                    return true;
                } catch (PackageManager.NameNotFoundException var2) {
                    return false;
                }
            }
        } else {
            return false;
        }
    }

    public static String getPhoneModel() {
        return Build.MODEL;
    }
}
